#!/usr/bin/env node

const http = require('http');

// 测试单个模板创建
const testTemplate = {
  id: 'test-template-001',
  name: '测试模板',
  description: '用于测试API连接的简单模板',
  type: 'txt2img',
  base_model: 'sd_xl_base_1.0.safetensors',
  prompt: 'a beautiful landscape',
  negative_prompt: 'blurry, low quality',
  sampler: 'DPM++ 2M Karras',
  steps: 20,
  width: 1024,
  height: 1024,
  cfg_scale: 7
};

function testCreateTemplate() {
  return new Promise((resolve) => {
    const postData = JSON.stringify({ template: testTemplate });
    
    console.log('🔄 测试API连接...');
    console.log('📦 发送数据:', JSON.stringify(testTemplate, null, 2));
    
    const options = {
      hostname: 'localhost',
      port: 3000,
      path: '/api/templates-db',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      },
      timeout: 5000
    };

    const req = http.request(options, (res) => {
      let data = '';
      
      console.log(`📡 状态码: ${res.statusCode}`);
      console.log(`📋 响应头:`, res.headers);
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        console.log(`📄 响应数据: ${data}`);
        try {
          const result = JSON.parse(data);
          resolve({ success: true, result });
        } catch (error) {
          console.error('❌ JSON解析失败:', error.message);
          resolve({ success: false, error: error.message, rawData: data });
        }
      });
    });

    req.on('error', (error) => {
      console.error('❌ 请求错误:', error.message);
      resolve({ success: false, error: error.message });
    });

    req.on('timeout', () => {
      console.error('❌ 请求超时');
      req.destroy();
      resolve({ success: false, error: '请求超时' });
    });

    req.write(postData);
    req.end();
  });
}

// 执行测试
async function main() {
  console.log('🚀 开始单模板测试...');
  const result = await testCreateTemplate();
  
  if (result.success) {
    console.log('✅ 测试成功!');
    console.log('📊 结果:', result.result);
  } else {
    console.log('❌ 测试失败!');
    console.log('💥 错误:', result.error);
    if (result.rawData) {
      console.log('📄 原始数据:', result.rawData);
    }
  }
}

main().catch(console.error);